package com.centling.smartSealForPhone.receiver;

import android.app.Activity;
import android.app.ActivityManager;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.NotificationCompat;
import android.text.TextUtils;

import com.centling.smartSealForPhone.R;
import com.centling.smartSealForPhone.activity.LoginActivity;
import com.centling.smartSealForPhone.event.ReceiveNotificationEvent;
import com.wsdk.service.BluetoothLeService;
import com.centling.smartSealForPhone.utils.ActivityCountManager;
import com.centling.smartSealForPhone.utils.LogUtil;

import org.greenrobot.eventbus.EventBus;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.List;

import cn.jpush.android.api.JPushInterface;

/**
 * JPushMessageReceiver
 *
 * @author fionera
 * @date 17-7-4
 */

public class JPushMessageReceiver
        extends BroadcastReceiver {
    private NotificationManager notificationManager;
    private int notificationId = 1000;
    public static String START_FROM_MSG = "start_from_msg";
    public static String MSG_INFO = "msg_info";

    @Override
    public void onReceive(Context context, Intent intent) {
        if (notificationManager == null) {
            notificationManager = (NotificationManager) context.getSystemService(
                    Context.NOTIFICATION_SERVICE);
        }
        Bundle bundle = intent.getExtras();
        LogUtil.d("JPushMessageReceiver Receive Msg:" + intent
                .getAction() + ", extras: " + (bundle != null ? bundle.toString() : "null"));

        if (bundle == null) {
            return;
        }

        if (TextUtils.equals(JPushInterface.ACTION_REGISTRATION_ID, intent.getAction())) {
            LogUtil.d("JPush用户注册成功");
        } else if (TextUtils.equals(JPushInterface.ACTION_MESSAGE_RECEIVED, intent.getAction())) {
            LogUtil.d("接受到推送下来的自定义消息");
            processCustomMessage(context, bundle);
        } else if (JPushInterface.ACTION_NOTIFICATION_RECEIVED.equals(intent.getAction())) {
            LogUtil.d("接受到推送下来的通知");
            receivingNotification(bundle);
        } else if (JPushInterface.ACTION_NOTIFICATION_OPENED.equals(intent.getAction())) {
            LogUtil.d("用户点击打开了通知");
            openNotification(bundle);
        }
    }

    private void processCustomMessage(final Context context, Bundle bundle) {
        String title = bundle.getString(JPushInterface.EXTRA_TITLE);
        LogUtil.d("title : " + title);
        String message = bundle.getString(JPushInterface.EXTRA_MESSAGE);
        LogUtil.d("message : " + message);
        int type = -1;
        try {
            JSONObject jsonObject = new JSONObject(message);
            type = jsonObject.optInt("businessType");
        } catch (JSONException e) {
            e.printStackTrace();
        }
        Activity currentActivity = ActivityCountManager.currentActivity();
        switch (type) {
            case 2:
                if (isAppOnForeground(context)) {
                    if (currentActivity != null && !(currentActivity instanceof LoginActivity)) {
                        kickOutUser(context);
                    } else {
                        notificationManager.notify(++notificationId,
                                createNotification(context, "您有一个踢出通知", new Intent()));
                    }
                }
                break;
            default:
                // 刷新我的页面左上角红点
                EventBus.getDefault().post(new ReceiveNotificationEvent(true));

                if (isAppOnForeground(context)) {
                    if (currentActivity != null) {
//                        context.startActivity(
//                                getIntentForJump(context, message, currentActivity.getClass()));
                        notificationManager.notify(++notificationId,
                                createNotification(context, "您有一个新的通知", new Intent()));
                    }
                } else {
                    if (currentActivity == null) {
                        notificationManager.notify(++notificationId,
                                createBroadCastNotification(context, "您有一个新的通知",
                                        getIntentForBroadcast(message,
                                                JPushAssistReceiver.ACTION_ASSIST_OPERATE)));
                    } else {
                        notificationManager.notify(++notificationId,
                                createNotification(context, "您有一个新的通知",
                                        getIntentForJump(context, message, currentActivity.getClass())));
                    }
                }
                break;
        }
    }

    private void kickOutUser(Context context) {
        BluetoothLeService.disconnect();
        context.startActivity(new Intent(context, LoginActivity.class)
                .setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK));
    }

    private boolean isAppOnForeground(Context context) {
        ActivityManager activityManager = (ActivityManager) context.getSystemService(
                Context.ACTIVITY_SERVICE);

        if (activityManager == null) {
            return false;
        }
        List<ActivityManager.RunningAppProcessInfo> appProcesses = activityManager
                .getRunningAppProcesses();
        if (appProcesses == null) {
            return false;
        }

        for (ActivityManager.RunningAppProcessInfo appProcess : appProcesses) {
            // importance for foreground judgement
            if (TextUtils.equals(appProcess.processName,
                    context.getPackageName()) && appProcess.importance == ActivityManager
                    .RunningAppProcessInfo.IMPORTANCE_FOREGROUND) {
                return true;
            }
        }
        return false;
    }

    private Intent getIntentForJump(Context context, String message, Class currentActivity) {
        return new Intent(context, currentActivity).addFlags(
                Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_SINGLE_TOP)
                .putExtra("newIntentType", "newIntentType")
                .putExtra(MSG_INFO, message);
    }

    private Intent getIntentForBroadcast(String message, String action) {
        return new Intent(action).putExtra(MSG_INFO, message);
    }

    private Notification createNotification(Context context, String message, Intent intent) {
        NotificationCompat.Builder builder = new NotificationCompat.Builder(context, "DefaultChannel");
        return builder.setContentTitle("智能盖章").setContentText(message).setSmallIcon(
                R.mipmap.ic_launcher).setTicker("智能盖章-新消息").setAutoCancel(true).setDefaults(
                Notification.DEFAULT_ALL).setContentIntent(
                PendingIntent.getActivity(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT))
                .build();
    }

    private Notification createBroadCastNotification(Context context, String message,
                                                     Intent intent) {
        NotificationCompat.Builder builder = new NotificationCompat.Builder(context,"DefaultChannel");
        return builder.setContentTitle("智能盖章").setContentText(message).setSmallIcon(
                R.mipmap.ic_launcher).setTicker("智能盖章-新消息").setAutoCancel(true).setDefaults(
                Notification.DEFAULT_ALL).setContentIntent(
                PendingIntent.getBroadcast(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT))
                .build();
    }

    private void receivingNotification(Bundle bundle) {
        String title = bundle.getString(JPushInterface.EXTRA_NOTIFICATION_TITLE);
        LogUtil.d("title : " + title);
        String message = bundle.getString(JPushInterface.EXTRA_ALERT);
        LogUtil.d("message : " + message);
        String extras = bundle.getString(JPushInterface.EXTRA_EXTRA);
        LogUtil.d("extras : " + extras);
        int notifyId = bundle.getInt(JPushInterface.EXTRA_NOTIFICATION_ID);
        LogUtil.d("notify : " + notifyId);
        if (notifyId > 0) {
            notificationManager.cancel(notifyId);
        }
    }

    private void openNotification(Bundle bundle) {
        String extras = bundle.getString(JPushInterface.EXTRA_EXTRA);
        String info;
        try {
            JSONObject extrasJson = new JSONObject(extras);
            info = extrasJson.optString("info");
            LogUtil.d(info);
        } catch (Exception e) {
            LogUtil.d("简直太糟糕了！！");
        }
    }
}
